/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
 *
 *
 * @param l1 ListNode类
 * @param l2 ListNode类
 * @return ListNode类
 */

/*
    有两条链表，一条链表是升序排列的，另一条链表是降序排列的。现在需要将这两条链表合并为一个新的升序链表，并返回。
*/
struct ListNode* mergeLists(struct ListNode* l1, struct ListNode* l2) {
    // write code here

    // 逆置l2( 降序-》升序 ）
    struct ListNode* rev = l2;
    struct ListNode* rev_head = NULL;
    while (rev) {
        struct ListNode* next = rev->next;
        rev->next = rev_head;
        rev_head = rev;
        rev = next;
    }
    l2 = rev_head;

    if (l1 == NULL)
        return l2;
    if (l2 == NULL)
        return l1;

    // 双指针
    struct ListNode* cur1 = l1;
    struct ListNode* cur2 = l2;
    // 新链表
    struct ListNode* head = NULL, * tail = NULL;
    while (cur1 && cur2) {
        int min = 0;
        if (cur1->val < cur2->val) {
            min = cur1->val;
            cur1 = cur1->next;
        } else {
            min = cur2->val;
            cur2 = cur2->next;
        }

        struct ListNode* NewNode = (struct ListNode*)malloc(sizeof(
                                       struct ListNode) * 1);
        NewNode->val = min;
        NewNode->next = NULL;
        if (head == NULL) {
            head = tail = NewNode;
        } else {
            tail->next = NewNode;
            tail = NewNode;
        }
    }
    // 链接剩余节点
    if (cur1)
        tail->next = cur1;
    else
        tail->next = cur2;
    return head;
}